package com.FrameWork.Synchoronization;

import java.util.Calendar;
import java.util.HashMap;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.FrameWork.Common.MyApplication;
import com.FrameWork.Entity.ProgressEntity;

/**
 * @author steven.jiang
 * 
 */
public class SynchLogicManager
{

	public static Context				  Context;
	public static Synchronization Synchronization = null;
	public static SynchConfig			      SynchConfig;

	public static void
	InitLogic(ISyncProcess process, SynchConfig config) throws Exception
	{
		// 初始化下载逻辑
		MyApplication.getInstance().DataProvider.Execute("DELETE FROM ML_PDADownloadLogic");

		HashMap<String, String> map = process.getDownloadLogic();
		// 更新下载逻辑
		if (map != null)
		{
			String SQL = "INSERT INTO ML_PDADownloadLogic (TableName,Table_Order,TimeStamp,Version,Active,Transferred,Keys) VALUES(?,?,0,?,1,0,?)";

			for (String tableName : map.keySet())
			{
				String value = map.get(tableName);
				String[] values = value.split(",");
				Object[] bindArgs = {
						tableName,
						values[0],
						config.Version,
						values[1] };
				MyApplication.getInstance().DataProvider.Execute(SQL, bindArgs);
			}
		}


	}

	public static void CleanDataBase() throws Exception
	{
		try
		{
			// 获取所有需要清空的表名
			Cursor reader = MyApplication.getInstance().DataProvider.getCursor("sqlite_master",
					new String[] { "name" },
					"type='table' and NAME NOT IN ('ML_SynchConfig','ML_PDADownloadLogic')",
					null,
					null,
					null,
					null);

			while (reader.moveToNext())
			{
				// 删除每张表的数据,并释放空间，SQLite没有TRUNCATE清空表命令，用VACUUM 命令来释放空间
				MyApplication.getInstance().DataProvider.Execute("DELETE FROM "
						+ reader.getString(0)
						+ ";VACUUM "
						+ reader.getString(0)
						+ ";");

			}
			//reader.close();

		}
		catch (Exception ex)
		{
			throw ex;
		}
	}

	/*public static Cursor getUploadTable(String version)
	{
		String condition= " type='table' and name like 'UPLOAD_%' and name not in ('UPLOAD_PHOTO')";
		return MyApplication.getInstance().getGlobalInfo().DataProvider.getCursor("sqlite_master",
				new String[] { "name" },
				condition,
				null,
				null,
				null,
				null);

	}*/

	public int GetUnuploadDataCount(ISyncProcess process)
	{
		 int count=0;
		 if(process != null)
		 {
			  TreeMap<Integer,String> hash = process.getUploadTablesAndLogic();
			  SQLiteDatabase db = MyApplication.getInstance().DataProvider.getReadableDatabase();
				
			  for (Integer key : hash.keySet()) {
					String[] values = hash.get(key).split(",");
					Cursor cursor = db.rawQuery("SELECT count(*) from " + values[0], null);
					if(cursor.moveToNext())
					{
						count += cursor.getInt(0);
					}
				}
			  db.close();
			  db = null;
			  
		 }
		 return count;
	}
	public static Cursor getDownloadTable(String version)
	{

		return MyApplication.getInstance().DataProvider.getCursor("ML_PDADownloadLogic",
				new String[] {
				"distinct TIMESTAMP",
		"TABLENAME" },
		null,
		null,
		null,
		null,
				"TABLE_ORDER ASC");
	}

	//获取数据表的主键名称
	static String getTableKeys(String tableName)
	{
		String key = null;
		Cursor cursor = null;
		try
		{

			cursor =MyApplication.getInstance().DataProvider.Query("SELECT Keys from ML_PDADownloadLogic where TableName='" + tableName + "'");
			if(cursor.moveToNext())
			{
				key = cursor.getString(0);
			}
		}
		finally
		{
			if(cursor !=null)
			{
				//cursor.close();
				cursor = null;
			}
		}
		return key;
	}

	public static boolean ParseData(Context context,String jsonarray, Synchronization sync,ProgressEntity entity) throws JSONException
	{
		Boolean Successful = false;

		// 解析返回的内容
		java.util.Date begin = Calendar.getInstance().getTime();
		JSONArray array = new JSONArray(jsonarray);// 获得json对象数组
		if(!array.isNull(0))
		{
			String msg = array.getJSONObject(0).getString("errmsg");
			if(msg.length()>0)
			{
				entity.Increment+=1;
				entity.Message = msg;
				sync.notifyObservers(entity.clone());
				return false;
			}
		}
		java.util.Date end = Calendar.getInstance().getTime();
		for (int i = 0; i < array.length(); i++)
		{
			begin = Calendar.getInstance().getTime();
			JSONObject o = array.getJSONObject(i);
			String tableName = o.getString("tablename");// 表名
			//查找该表是否存在
			android.database.sqlite.SQLiteCursor reader = null;
			try
			{
				reader = MyApplication.getInstance().DataProvider.getCursor("sqlite_master", new String[]{"name"}, "type='table' and lower(NAME)=lower('" + tableName +"') ", null, null, null, null);
				if(!reader.moveToNext())
				{

					if(sync != null)
					{
						entity.Increment+=1;
						entity.Message = tableName + "不存在";
						sync.notifyObservers(entity.clone());
					}

					continue;
				}
			}
			finally
			{
				if(reader != null)
				{
					reader.close();
					reader = null;
				}
			}

			Boolean success = o.getBoolean("success");// 是否成功
			String errmsg = o.getString("errmsg");// 错误信息
			double timeSpan = o.getDouble("timespan");// 最新时间戳
			android.database.sqlite.SQLiteCursor cursor = null;
			try
			{
				Boolean successful=false;
				if (success)
				{

					JSONArray rowarr = o.getJSONArray("row");// 数据部分

					int count=0;
					String ValuesSQL ="";
					//Build Insert SQl String
					String InsertSQL = "INSERT OR REPLACE INTO " +tableName + "(";

					SQLiteStatement InsertStatement = null;
					MyApplication.getInstance().DataProvider.myDataBase.beginTransaction();
					try
					{

						for (int j = 0; j < rowarr.length(); j++)
						{
							//contentvalues.clear();
							JSONObject objrow = rowarr.getJSONObject(j);

							JSONArray namearray = objrow.names();
							if(ValuesSQL.length()==0)
							{
								for(int ColumnIndex=0;ColumnIndex<namearray.length();ColumnIndex++)
								{
									InsertSQL +=namearray.getString(ColumnIndex) + ",";
									ValuesSQL+="?,";
								}
								InsertSQL=InsertSQL.substring(0, InsertSQL.length()-1);
								ValuesSQL = ValuesSQL.substring(0, ValuesSQL.length()-1);
								InsertSQL +=") VALUES(" + ValuesSQL + ")";
								InsertStatement = MyApplication.getInstance().DataProvider.CompileStatement(InsertSQL);

							}
							String v="";
							for (int index=0;index<namearray.length();index++)
							{
								String columnname = namearray.getString(index);// 列名
								Object cellvalue = objrow.get(columnname);// 单元格值
								if ("null".equals(cellvalue))
								{
									cellvalue = null;

								}

								if(cellvalue == null)
								{
									InsertStatement.bindNull(index+1);
								}
								else
								{
									v+="'"+cellvalue.toString()+"',";
									InsertStatement.bindString(index+1, cellvalue.toString());

								}
							}
							InsertStatement.executeInsert();
							count=j+1;

						}

						successful = true;
					}
					catch(Exception err)
					{
						err.printStackTrace();
						if(sync != null)
						{
							entity.Increment+=1;
							entity.Message = tableName + err.getMessage();
							sync.notifyObservers(entity.clone());
						}

					}
					finally
					{
						if(cursor != null)
						{
							cursor.close();
							cursor = null;

						}
						if(InsertStatement != null)
						{
							InsertStatement.close();
							InsertStatement = null;

						}
						MyApplication.getInstance().DataProvider.myDataBase.setTransactionSuccessful();
						MyApplication.getInstance().DataProvider.myDataBase.endTransaction();

					}
					end = Calendar.getInstance().getTime();
					if (successful && timeSpan > 0)
					{
						// 下载解析全部完成更新同步时间戳
						String sql = "update ml_pdadownloadlogic set Transferred=0,TimeStamp="
								+ timeSpan
								+ " where Active=1 and TableName='"
								+ tableName
								+ "' and Version='"
								+ SynchConfig.Instance(context).Version
								+ "' ";

						MyApplication.getInstance().DataProvider.Execute(sql);
						if(sync != null)
						{
							entity.Increment+=1;
							entity.Message = tableName +"下载数据" + count+ "条,耗时" + (end.getTime() - begin.getTime()) + "毫秒";
							sync.notifyObservers(entity.clone());
						}
					}

				}
				else
				{
					if(sync != null)
					{
						entity.Increment+=1;
						entity.Message = tableName + "下载失败：\r\n" + errmsg;
						sync.notifyObservers(entity.clone());
					}
				}
				Successful = true;
			}
			catch (Exception e)
			{
				Successful = false;
				e.printStackTrace();
				if(sync != null)
				{
					entity.Increment+=1;
					entity.Message = "表" + tableName + "异常\r\n" + e.getMessage();
					sync.notifyObservers(entity.clone());
				}
			}

		}
		return Successful;
	}

	public static void CleanUploadTable() throws Exception
	{
		try
		{
			String condition= " type='table' and name like 'UPLOAD_%' and name not in ('UPLOAD_PHOTO')";
			// 获取所有需要清空的表名photo表单独删除
			Cursor reader = MyApplication.getInstance().DataProvider.getCursor("sqlite_master",
					new String[] { "name" },
					condition,
					null,
					null,
					null,
					null);

			while (reader.moveToNext())
			{
				// 删除每张表的数据,并释放空间，SQLite没有TRUNCATE清空表命令，用VACUUM 命令来释放空间
				MyApplication.getInstance().DataProvider.Execute("DELETE FROM "
						+ reader.getString(0) +" WHERE DIRTY=2"
						+ ";VACUUM "
						+ reader.getString(0)
						+ ";");

			}
			//reader.close();

		}
		catch (Exception ex)
		{

			throw ex;
		}
	}
}
